package net.matuschek.http;

import java.util.*;
import java.text.*;

/**
 * Common place for date utils.
 * Copied and modified from org.apache.tomcat.util.buf
 * @author <a href="mailto:d.stucky@insiders.de">Daniel Stucky</a>
 * @version $Revision: 1.1 $ 
 **/

public class HTTPDateTool
{
    /** GMT timezone - all HTTP dates are on GMT
    */
    public final static TimeZone GMT_ZONE = TimeZone.getTimeZone("GMT");

    /** format for RFC 1123 date string -- "Sun, 06 Nov 1994 08:49:37 GMT"
    */
    public final static String RFC1123_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z";

    // format for RFC 1036 date string -- "Sunday, 06-Nov-94 08:49:37 GMT"
    public final static String rfc1036Pattern = "EEEEEEEEE, dd-MMM-yy HH:mm:ss z";

    // format for C asctime() date string -- "Sun Nov  6 08:49:37 1994"
    public final static String asctimePattern = "EEE MMM d HH:mm:ss yyyy";
   
	/** 
	DateFormat to be used to format dates.
    */
    public final static DateFormat rfc1123Format = new SimpleDateFormat( RFC1123_PATTERN, Locale.US );
       
    public final static DateFormat rfc1036Format =	new SimpleDateFormat( rfc1036Pattern, Locale.US );
    
    public final static DateFormat asctimeFormat =	new SimpleDateFormat( asctimePattern, Locale.US );

	
	/**
	*/
	public static String format1123( Date d, DateFormat df )
	{
        long dt = d.getTime() % 1000;
        if ( (rfc1123DS != null) && (dt == rfc1123Sec) )
            return rfc1123DS;
        rfc1123DS  = df.format( d );
        rfc1123Sec = dt;
        return rfc1123DS;
    } 

       
    /**
	Parses a string for a date of the format rfc1123Format, rfc1036Format or asctimeFormat.
	Returns -1, if any parameter is null or the string is of a not supported format.
	@return the parsed date in milliseconds
    */
    public static long parseDate( String dateString )
	{
		DateFormat [] format = { rfc1123Format, rfc1036Format, asctimeFormat };
		return parseDate( dateString,format );
    }
    

	/**
	Parses a string for a date of one of the given formats.
	Returns -1, if any parameter is null or the string is of a not supported format.
	@return the parsed date in milliseconds
	*/
	public static long parseDate( String dateString, DateFormat[] format )
	{
		if ( dateString != null && format != null )
		{
			Date date = null;
			for(int i=0; i < format.length; i++)
			{
				try
				{
					date = format[i].parse( dateString );
					return date.getTime();
				}
				catch (ParseException e)
				{}
				catch (StringIndexOutOfBoundsException e)
				{}
			}
		}
		return -1;
    }    

    private static String rfc1123DS;
    private static long   rfc1123Sec;

    static
	{
		rfc1123Format.setTimeZone(GMT_ZONE);		
		rfc1036Format.setTimeZone(GMT_ZONE);
		asctimeFormat.setTimeZone(GMT_ZONE);
    }
}
